package hci.utils;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class MaxLengthTextDocument extends PlainDocument {
	// Reference:
	// http://www.andrels.com/wp-en_US/index.php/2009/09/setting-maximum-number-of-characters-in-jtextfield/

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	// Store maximum characters permitted
	private int maxChars;

	public int getMaxChars() {
		return maxChars;
	}

	public void setMaxChars(int maxChars) {
		this.maxChars = maxChars;
	}

	@Override
	public void insertString(int offs, String str, AttributeSet a)
			throws BadLocationException {
		if (str != null && (getLength() + str.length() < maxChars)) {
			super.insertString(offs, str, a);
		}
	}

}
